<template>
  <!-- !项目概况 -->
  <div class="overview">
    <a-row :gutter="[8, 8]">
      <a-col :span="24">
        <!-- 统计信息 -->
        <a-card size="small">
          <a-card-grid :style="gridStyle">
            <a-row :gutter="[0, 0]">
              <a-col :span="24" class="p-10">
                <a-statistic :value="detail.rent_in_contract">
                  <template #title>
                    <span class="fs-12">在租合同数</span>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="24" class="statis-desc">
                <a-space>
                  <span>房源数量：</span>
                  <span class="num">{{ detail.room_count }}</span>
                </a-space>
              </a-col>
            </a-row>
          </a-card-grid>
          <a-card-grid :style="gridStyle">
            <a-row :gutter="[0, 0]">
              <a-col :span="24" class="p-10">
                <a-statistic :value="detail.management_area">
                  <template #title>
                    <span class="fs-12">管理面积</span>
                  </template>
                  <template #suffix>
                    <span class="fs-12">m²</span>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="24" class="statis-desc">
                <a-space>
                  <span>建筑面积：</span>
                  <span class="num">
                    {{ Number(detail.property_area).toFixed(2) }}m²
                  </span>
                </a-space>
              </a-col>
            </a-row>
          </a-card-grid>
          <a-card-grid :style="gridStyle">
            <a-row :gutter="[0, 0]">
              <a-col :span="24" class="p-10">
                <a-statistic :value="detail.rent_in_real_price" :precision="2">
                  <template #title>
                    <span class="fs-12">在租实时均价</span>
                  </template>
                  <template #suffix>
                    <span class="fs-12">元/m²·天</span>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="24" class="statis-desc">
                <a-space>
                  <span>在租面积：</span>
                  <span class="num">
                    {{ Number(detail.rent_in_area).toFixed(2) }}m²
                  </span>
                </a-space>
              </a-col>
            </a-row>
          </a-card-grid>
          <a-card-grid :style="gridStyle">
            <a-row :gutter="[0, 0]">
              <a-col :span="24" class="p-10">
                <!-- <a-row type="flex" justify="space-between" align="middle"> -->
                <!-- <a-col> -->
                <a-statistic
                  :value="detail.rent_in_precent"
                  :valueStyle="{
                    color:
                      Number(detail.rent_in_precent) < 50
                        ? '#faad14'
                        : '#52c41a',
                  }"
                >
                  <template #title>
                    <span class="fs-12">出租率</span>
                  </template>
                  <template #suffix>
                    <span class="fs-12">%</span>
                  </template>
                </a-statistic>
              </a-col>
              <a-col :span="24" class="statis-desc">
                <a-space>
                  <span>待租面积：</span>
                  <span class="num">
                    {{ Number(detail.to_rent_area).toFixed(2) }}m²
                  </span>
                </a-space>
              </a-col>
            </a-row>
          </a-card-grid>
        </a-card>
      </a-col>
      <a-col :span="24">
        <!-- 租客分析 -->
        <a-card size="small" title="租客分析">
          <a-row :gutter="8">
            <a-col :span="8">
              <div class="text-title">租客行业</div>
              <div v-show="industryInfo.length" :id="industryChartId"></div>
              <div class="empty" v-if="!industryInfo.length">
                <a-empty :image="simpleImage" />
              </div>
            </a-col>
            <a-col :span="8">
              <div class="text-title">租客标签</div>
              <div v-show="tagInfo.length" :id="tagChartId"></div>
              <div class="empty" v-if="!tagInfo.length">
                <a-empty :image="simpleImage" />
              </div>
            </a-col>
            <a-col :span="8">
              <div class="text-title">租赁面积排行</div>
              <div v-if="areaList.length">
                <a-row
                  :gutter="8"
                  align="middle"
                  type="flex"
                  :wrap="false"
                  v-for="(item, index) of areaList"
                  :key="item.id"
                  class="mt-10"
                >
                  <a-col flex="40px">
                    <div
                      class="rank-index"
                      :class="{
                        'bg-green': index === 0,
                        'bg-blue': index === 1,
                        'bg-purple': index === 2,
                        'bg-orange': index === 3,
                        'bg-pink': index === 4,
                      }"
                    >
                      {{ index + 1 }}
                    </div>
                  </a-col>
                  <a-col
                    flex="auto"
                    class="nowrap"
                    @click="onOwnerClick(item.owner_id)"
                  >
                    <a-tooltip>
                      <template #title>{{ item.owner_name }}</template>
                      <span class="link">{{ item.owner_name || "--" }}</span>
                    </a-tooltip>
                  </a-col>
                  <a-col flex="100px" class="text-right">
                    {{ item.lease_areas }} ㎡</a-col
                  >
                </a-row>
              </div>
              <div class="empty" v-else>
                <a-empty :image="simpleImage" />
              </div>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
      <a-col :span="24">
        <a-card size="small" title="租金单价排行">
          <a-table
            :dataSource="rentPriceList"
            :columns="priceColumns"
            :pagination="false"
            rowKey="id"
            bordered
            size="small"
          >
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'owner_name'">
                <span class="link" @click="onOwnerClick(record.owner_id)">{{
                  text || "--"
                }}</span>
              </template>
              <template v-if="column.key === 'rent_price'">
                <span>
                  {{
                    record.rent_price
                      ? record.rent_price + record.price_unit
                      : "-"
                  }}
                </span>
              </template>
              <template v-if="column.key === 'lease_area'">
                <span>
                  {{ text + record.lease_square_unit }}
                </span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="ownerDetailVisible = false"
    />
  </div>
</template>
<script>
import { defineComponent, reactive, toRefs, nextTick, watch } from "vue";
import OwnerDetailDrawer from "../../../views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import request from "../../../common/utils/request";
import { Chart } from "@antv/g2";
import { Empty } from "ant-design-vue";
import BLCOMMON from "bl-common-vue3";
import { useRoute } from "vue-router";

export default defineComponent({
  name: "VillageOverview",
  props: {
    // 项目详情或楼宇详情
    detail: {
      type: Object,
      default: () => ({}),
    },
    // 类型 village项目 build楼宇
    type: {
      type: String,
      default: "village",
    },
  },
  components: { OwnerDetailDrawer },
  setup(props, { emit }) {
    const INDUSTRY = "industry";
    const TAG = "tag";
    const COUNT_LIMIT = 5;

    const ROUTE = useRoute();
    watch(
      () => ROUTE.name,
      () => {
        state.ownerDetailVisible = false;
      }
    );
    const state = reactive({
      industryInfo: [],
      industryChartId: "",
      tagInfo: [],
      tagChartId: "",
      chart: {},
      areaList: [],
      params: {},
      rentPriceList: [],
      ownerDetailVisible: false,
      ownerId: 0,
    });

    /** 查看租客 */
    const onOwnerClick = (id) => {
      state.ownerId = id;
      state.ownerDetailVisible = true;
    };

    /**  获取租金单价排行*/
    const getRentPriceList = () => {
      request
        .get("/org", "/owner/leasePriceRank", {
          ...state.params,
          limit: COUNT_LIMIT,
        })
        .then((res) => {
          state.rentPriceList = res.rankList;
        });
    };

    /** 获取租赁面积排行 */
    const getAreaList = () => {
      request
        .get("/org", "/owner/leaseAreaRank", {
          ...state.params,
          limit: COUNT_LIMIT,
        })
        .then((res) => {
          state.areaList = res.rankList;
        });
    };

    /** 租客行业分析 */
    const getIndustryInfo = () => {
      state.industryChartId = `${INDUSTRY}Chart_${props.type}_${props.detail.id}`;
      request
        .get("/org", "/board/industryAnalyse", state.params)
        .then((res) => {
          state.industryInfo = res.list.map((item) => ({
            name: item.industryName,
            percent: item.percent,
            total: item.percent,
          }));

          nextTick(() => {
            initChart(INDUSTRY, state.industryInfo);
          });
        });
    };

    /** 租客标签分析 */
    const getTagInfo = () => {
      state.tagChartId = `${TAG}Chart_${props.type}_${props.detail.id}`;
      request.get("/org", "/board/tagAnalyse", state.params).then((res) => {
        state.tagInfo = res.list.map((item) => ({
          name: item.tagName,
          percent: item.percent,
          total: item.percent,
        }));

        nextTick(() => {
          initChart(TAG, state.tagInfo);
        });
      });
    };

    /** 初始化图表 */
    const initChart = (chartName, data) => {
      if (!state.chart[chartName]) {
        state.chart[chartName] = new Chart({
          container: state[`${chartName}ChartId`],
          autoFit: true,
          height: 160,
          padding: [0, 0, 0, -260],
        });
      }
      state.chart[chartName].changeData(data);
      state.chart[chartName].coordinate("theta", {
        radius: 0.65,
        innerRadius: 0.8,
      });
      state.chart[chartName].tooltip({
        showCrosshairs: false,
        shared: false,
        showMarkers: false,
      });
      state.chart[chartName].legend("name", {
        position: "right",
        custom: true,
        offsetX: -140,
        items: data.map((obj, index) => {
          return {
            name: obj.name + obj.total,
            value: obj.percent,
            marker: {
              symbol: "square",
              style: {
                r: 5,
                fill: state.chart[chartName].getTheme().colors10[index],
              },
            },
          };
        }),
        itemValue: {
          style: {
            fill: "#999",
          },
          formatter: (val) => `(${val}%)`,
        },
      });
      state.chart[chartName]
        .interval()
        .adjust("stack")
        .position("percent")
        .color("name")
        .style({
          fillOpacity: 1,
        })
        .state({
          active: {
            style: (element) => {
              const shape = element.shape;
              return {
                lineWidth: 10,
                stroke: shape.attr("fill"),
                strokeOpacity: shape.attr("fillOpacity"),
              };
            },
          },
        });

      // 移除图例点击过滤交互
      state.chart[chartName].removeInteraction("legend-filter");
      state.chart[chartName].interaction("element-active");

      state.chart[chartName].render();
    };

    /** 初始化 */
    const init = () => {
      if (!props.detail.id) {
        return;
      }
      state.params[`${props.type}_id`] = props.detail.id;
      getIndustryInfo();
      getTagInfo();
      getAreaList();
      getRentPriceList();
    };

    init();

    return {
      gridStyle: `width:25%; padding: 0px`,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      priceColumns,
      ...toRefs(state),
      onOwnerClick,
    };
  },
});

const priceColumns = [
  {
    title: "排名",
    customRender: ({ text, record, index }) => `${index + 1}`,
  },
  {
    title: BLCOMMON.utils.L("租客"),
    dataIndex: "owner_name",
    key: "owner_name",
  },
  {
    title: "租赁单价",
    dataIndex: "rent_price",
    key: "rent_price",
  },
  {
    title: "租赁天数",
    dataIndex: "lease",
  },
  {
    title: "租赁面积",
    dataIndex: "lease_area",
    key: "lease_area",
  },
  {
    title: BLCOMMON.utils.L("房源"),
    dataIndex: "room_info",
  },
];
</script>
<style lang="less" scoped>
.overview {
  width: 100%;
  font-size: 12px;

  .statis-desc {
    padding: 10px;
    border-top: 1px solid #f1f1f1;
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    line-height: 24px;
    .num {
      font-size: 14px;
      color: rgba(0, 0, 0, 1);
    }
  }
  .rank-index {
    width: 20px;
    height: 20px;
    // border: 1px solid rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    // background-color: #314659;
    color: #fff;
    font-size: 12px;
  }

  .empty {
    width: 100%;
    height: 160px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
